<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/2/13
 * Time: 下午2:54
 */
namespace app\common\model;

use think\Exception;
use think\Loader;


class InvitePoster extends Common
{
    /**
     * 获取用户的推广海报
     *
     * @param array $user 当前用户
     * @return string
     */
    static public function spread($user)
    {
        //获取推广海报设置
        $poster = Settings::getSettings(H_SETTINGS_POSTER_SPREAD);

        //生成海报
        return self::generate($user, "spread", $poster);
    }

    /**
     * 生成海报
     *
     * @param array $user 当前用户
     * @param string $type 海报类型
     * @param array $poster 海报设置
     * @return string
     */
    static private function generate($user, $type, $poster)
    {
        //海报存储路径
        $savePath = config("public_path") . '/' . config("poster_path") . '/' . $type;

        //创建路径
        self::createDir($savePath);

        //生成文件名
        $fileName = md5(json_encode(array("user_uid"=>$user["id"],"poster"=>$poster))) . ".png";

        //文件完整名
        $fullName = $savePath . '/' . $fileName;

        //如果海报不存在，则新建海报
        if (!is_file($fullName))
        {
            set_time_limit(0);
            @ini_set('memory_limit', '256M');

            //获取背景图资源
            $background = self::createImage(get_whole_image($poster["background"]));

            $width = imagesx($background);
            $height = imagesy($background);

            $target = imagecreatetruecolor($width, $height);

            imagecopy($target, $background, 0, 0, 0, 0, $width, $height);
            imagedestroy($background);

            //去除海报中的背景图
            unset($poster["background"]);

            foreach ($poster as $item)
            {
                $item = self::getRealData($item);

                //头像
                if ($item["type"] == "avatar")
                {
                    $avatar = preg_replace('/\\/0$/i', '/96', get_whole_image('/static/images/default_logo.png'));
                    $target = self::mergeImage($target, $item, $avatar,$width,$height);
                }
                //二维码
                else if ($item["type"] == "qr")
                {
                    //生成二维码
                    $qr = self::getQR($user, $item["size"]);

                    $target = self::mergeImage($target, $item, get_whole_image($qr),$width,$height);
                }
                //昵称
                else if ($item["type"] == "nickname")
                {
                    $target = self::mergeText($target, $item, $user['nick_name'],$width,$height);
                }
            }

            //生成图像
            imagepng($target, $fullName);
            //销毁图像资源
            imagedestroy($target);
        }

        //返回海报地址
        return get_whole_image(config("poster_path") . '/' . $type . '/' . $fileName);
    }

    /**
     * 根据图片URL创建图片资源
     *
     * @param string $image 图片URL
     * @return resource
     * @throws ServerException
     */
    static private function createImage($image)
    {
        //检测是否为图片是否有效
        if (!check_web_image($image))
        {
            throw new ServerException('此图片文件无效' . ":" . $image);
        }

        //获取文件内容
        $content = file_get_contents($image);

        //根据图片内容创建图片资源
        return imagecreatefromstring($content);
    }

    /**
     * 去除数据中无效的字符
     *
     * @param $data
     * @return mixed
     */
    static private function getRealData($data)
    {
        //去除像素单位
        $data['left'] = intval(str_replace('px', '', $data['left'])) * 2;
        $data['top'] = intval(str_replace('px', '', $data['top'])) * 2;
        $data['width'] = intval(str_replace('px', '', $data['width'])) * 2;
        $data['height'] = intval(str_replace('px', '', $data['height'])) * 2;

        //如果存在大小字段
        if (array_key_exists("size", $data))
        {
            $data['size'] = intval(str_replace('px', '', $data['size'])) * 2;
        }

        //如果存在图片
//        $data['src'] = get_whole_image($data['src']);

        return $data;
    }

    /**
     * 合并图像
     *
     * @param resource $target 目标图像
     * @param array $data 规则数据
     * @param string $image 待合并的图像地址
     * @return mixed
     */
    static private function mergeImage($target, $data, $image,$target_w,$target_h)
    {
        //图片资源
        $image = self::createImage($image);

        $wp = $target_w/640;
        $hp = $target_h/1008;

        //获取图片的尺寸
        $width = imagesx($image);
        $height = imagesy($image);

        //放置图像
        imagecopyresized($target, $image, $data['left']*$wp, $data['top']*$wp
            , 0, 0, $data['width']*$wp, $data['height']*$wp, $width, $height);

        //销毁图像资源
        imagedestroy($image);

        //返回合并后的图片资源
        return $target;
    }

    /**
     * 合并文本内容
     *
     * @param resource $target 目标图像
     * @param array $data 规则数据
     * @param string $text 待合并的文本
     * @return mixed
     */
    static private function mergeText($target, $data, $text,$target_w,$target_h)
    {
        $wp = $target_w/640;
        $hp = $target_h/1008;

        //处理颜色
        $color = self::hex2rgb($data['color']);
        $color = imagecolorallocate($target, $color['red'], $color['green'], $color['blue']);

        //字体
        $font = config("public_path") . '/' . "/static/fonts/FZKTJW.TTF";

        //添加文本到图像
        imagettftext($target, $data['size'], 0, $data['left']*$wp, $data['top']*$wp + $data['size'], $color, $font, $text);

        //返回处理后的资源
        return $target;
    }

    /**
     * 将16进制色转换为RGB色
     *
     * @param string $color 16进制色
     * @return array
     * @throws ServerException
     */
    static private function hex2rgb($color)
    {
        //去除#号
        if ($color[0] == '#')
        {
            $color = substr($color, 1);
        }


        if (strlen($color) == 6)
        {
            list($red, $green, $blue) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
        }
        else if (strlen($color) == 3)
        {
            list($red, $green, $blue) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
        }
        else
        {
            throw new ServerException(translate("Poster-hex2rgb:illegal_color"));
        }

        //将16进制色转换为RGB色
        $red = hexdec($red);
        $green = hexdec($green);
        $blue = hexdec($blue);

        //返回颜色值
        return array(
            "red" => $red,
            "green" => $green,
            "blue" => $blue
        );
    }

    /**
     * 根据用户生成二维码
     *
     * @param array $user 当前用户
     * @param int $size 栅格大小
     * @return string
     * @throws ServerException
     */
    static public function getQR($user, $size = 3)
    {
        //导入qrcode库
        Loader::import("phpqrcode.qrlib");

        //生成二维码的数据
        $data = get_regis_url($user);

        //保存路径
        $savePath = config("public_path") . '/' . config("qrcode_path");
        //创建路径
        self::createDir($savePath);

        $guige = 'H';//可被覆盖范围 最大

        //文件名
        $fileName = 'u'.$user['id'].$guige.".png";
        //完整名称
        $fullName = $savePath . '/' .$fileName;
        if(!file_exists($fullName)){
            try
            {
                \QRcode::png($data, $fullName, $guige, 30, 2);
            }
            catch (Exception $exception)
            {
                throw new ServerException($exception->getMessage());
            }
        }
        return config("qrcode_path") . '/' .$fileName;

    }

    /**
     * 创建文件层级
     *
     * @param string $path 路径
     * @throws ServerException
     */
    static private function createDir($path)
    {
        //如果路径存在，则不做任何处理
        if (is_dir($path))
        {
            return;
        }
        else
        {
            //第三个参数是“true”表示能创建多级目录
            $result = mkdir($path, 0777, true);

            //创建目录失败
            if (!$result)
            {
                throw new ServerException('创建目录失败');
            }
        }

    }
}